<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽</title>
    <style>
        #box {
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: aqua;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div id="box"></div>

    <script>
        // 思路一: 盒子移动后的位置 = 盒子移动前的位置 + 鼠标移动的距离
        // 思路二: 盒子移动后的位置 = 鼠标移动后的位置 - 鼠标距离盒子的距离
        const el = document.querySelector('#box')
        // 鼠标按下
        el.onmousedown = function (e) {
            // 鼠标相对盒子的位置 
            let offsetX = e.clientX - el.offsetLeft
            let offsetY = e.clientY - el.offsetTop

            document.onmousemove = function (e) {
                el.style.left = e.clientX - offsetX + 'px'
                el.style.top = e.clientY - offsetY + 'px'
            }
            // 鼠标松开
            el.onmouseup = function () {
                document.onmousemove = null;
                document.onmouseup = null;
                if (el.releaseCapture) {
                    el.releaseCapture();//释放全局捕获   
                }
            }
        }

    </script>

</body>

</html>